package com.conncui.common.json.impl;

import com.conncui.common.json.dao.Json;
import com.fasterxml.jackson.core.JsonFactory;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.type.TypeFactory;

import java.io.IOException;
import java.util.List;

/**
 * Created by ucui on 2017/3/5.
 */

public class JacksonImpl implements Json{

    static ObjectMapper sObjectMapper = new ObjectMapper();
    static JsonFactory mJsonFactory = new JsonFactory();
    @Override
    public String objectToString(Object object) {
        String result = null;
        try {
            result = sObjectMapper.writeValueAsString(object);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        return result;
    }

    @Override
    public <T> T stringToObject(String jsonString, Class<T> tClass) {
        T result = null;
        try {
            result = sObjectMapper.readValue(jsonString, tClass);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return result;
    }

    @Override
    public <T> List<T> stringToObjectList(String jsonString, Class<T> tClass) {
        //http://stackoverflow.com/questions/6349421/how-to-use-jackson-to-deserialise-an-array-of-objects
        List<T> result = null;
        try {
            result = sObjectMapper.readValue(jsonString,
                    TypeFactory.
                            defaultInstance()
                            .constructCollectionType(List.class, tClass));
        } catch (IOException e) {
            e.printStackTrace();
        }
        return result;
    }

    @Override
    public String objectListToString(Object objectList) {
        String result = null;
        try {
            result = sObjectMapper.writeValueAsString(objectList);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        return result;
    }
}